<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>全选练习</title>
  </head>
  <body>
    <form method="post" action="">
      你爱好的运动是？<input type="checkbox" id="checkedAllBox" />全选/全不选

      <br />
      <input type="checkbox" name="items" value="足球" />足球
      <input type="checkbox" name="items" value="篮球" />篮球
      <input type="checkbox" name="items" value="羽毛球" />羽毛球
      <input type="checkbox" name="items" value="乒乓球" />乒乓球
      <br />
      <input type="button" id="checkedAllBtn" value="全　选" />
      <input type="button" id="checkedNoBtn" value="全不选" />
      <input type="button" id="checkedRevBtn" value="反　选" />
      <input type="button" id="sendBtn" value="提　交" />
    </form>

    <script>
      var selectAll = document.getElementById("checkedAllBtn");
      var checkedNoBtn = document.getElementById("checkedNoBtn");
      var checkedRevBtn = document.getElementById("checkedRevBtn");
      var sendBtn = document.getElementById("sendBtn");
      var checkedAllBox = document.getElementById("checkedAllBox");

      var items = document.getElementsByName("items");

      //全选
      selectAll.onclick = function () {
        check(true, items);
        checkedAllBox.checked =true;

      };

      //全不选
      // checkedNoBtn.onclick =check(false,items);  //要在匿名函数内调用
      checkedNoBtn.onclick = function () {
        check(false, items);
        checkedAllBox.checked =false;

      };

      //反选
      checkedRevBtn.onclick = function () {
        checkedAllBox.checked =true;
        for (let i = 0; i < items.length; i++) {
          items[i].checked = !items[i].checked;
          if(!items[i].checked){
            checkedAllBox.checked =false;
          }


        }
      };

      //提交
      sendBtn.onclick = function () {
        for (let i = 0; i < items.length; i++) {
          if (items[i].checked) {
            alert(items[i].value);
          }
        }
      };

      //    全选/全不选
      checkedAllBox.onclick = function () {
        for (let i = 0; i < items.length; i++) {
          items[i].checked = checkedAllBox.checked;
        }
      };

      for (let i = 0; i < items.length; i++) {
        items[i].onclick = function () {
          checkedAllBox.checked = true;
          for (let j = 0; j < items.length; j++) {
            if (!items[j].checked) {
              checkedAllBox.checked = false;
            }
          }
        };
      }

      function check(op, items) {
        for (let i = 0; i < items.length; i++) {
          items[i].checked = op;
        }
      }
    </script>
  </body>
</html>
